package com.jinke.uang.main;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jinke.uang.AppApplication;
import com.jinke.uang.R;
import com.jinke.uang.adapter.MainAdapter;
import com.jinke.uang.app_link.AppLink;
import com.jinke.uang.base.BaseNormalActivity;
import com.jinke.uang.base.BaseResponse;
import com.jinke.uang.bean.UpdateData;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.cache.Acache;
import com.jinke.uang.cache.AcacheKeys;
import com.jinke.uang.common.DialogManager;
import com.jinke.uang.common.NoDoubleClickListener;
import com.jinke.uang.common.UserInfo;
import com.jinke.uang.constant.HttpConstant;
import com.jinke.uang.model.MainModule;
import com.jinke.uang.presenter.CommonPresenter;
import com.jinke.uang.rxbus.EventMsg;
import com.jinke.uang.rxbus.Events;
import com.jinke.uang.rxbus.RxBus;
import com.jinke.uang.ui.fragment.MineFragment;
import com.jinke.uang.utils.ApkUtils;
import com.jinke.uang.utils.AssetsUtils;
import com.jinke.uang.utils.StringUtils;
import com.jinke.uang.utils.ToastUtils;
import com.jinke.uang.view.MyViewPager;
import com.jinke.uang.view.UpdateVersionDialog;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * 首页界面
 */
@SuppressLint("CheckResult")
@Route(name = "首页", path = RouterMap.MAIN_ACTIVITY_PAGE)
public class MainActivity extends BaseNormalActivity<CommonPresenter, MainModule> {
    @BindView(R.id.viewpager)
    MyViewPager viewPager;
    @BindView(R.id.relHome)
    RelativeLayout relHome;
    @BindView(R.id.relMycenter)
    RelativeLayout relMycenter;
    private MainAdapter adapter;
    private List<Fragment> fragmentList = new ArrayList<>();
    private UpdateVersionDialog updateVersionDialog;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        MainFragment mainFragment = new MainFragment();
        MineFragment mineFragment = new MineFragment();
        fragmentList.add(mainFragment);
        fragmentList.add(mineFragment);
        adapter = new MainAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(2);
        viewPager.setCurrentItem(0);

        relHome.setSelected(true);
        relHome.setOnClickListener(viewclick);
        relMycenter.setOnClickListener(viewclick);

    }

    @Override
    protected void onUIReady() {
        AssetsUtils.copyDB();
        RxBus.getInstance().toObservable().map(new Function<Object, EventMsg>() {
            @Override
            public EventMsg apply(Object o) throws Exception {
                return (EventMsg) o;
            }
        }).subscribe(new Consumer<EventMsg>() {
            @Override
            public void accept(EventMsg eventMsg) throws Exception {
                if (Events.UPDATE.equals(eventMsg.getMsg())) {
                    mPresenter.getData(HttpConstant.GOOGLE_PLAY_UPDATE_INFO, null);
                } else if (Events.LOGOUT.equals(eventMsg.getMsg())) {
                    viewPager.setCurrentItem(0);
                    relHome.setSelected(true);
                    relMycenter.setSelected(false);
                }
            }
        });
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                String install = Acache.get(AppApplication.getContext()).getAsString(AcacheKeys
                        .IS_INSTALL);
                if (TextUtils.isEmpty(install)) {
                    AppLink.getInstance().init(AppApplication.getContext());
                }
            }
        }, 3000);
    }

    /**
     * 按钮点击事件的处理
     */
    private NoDoubleClickListener viewclick = new NoDoubleClickListener() {

        @Override
        public void onNoDoubleClick(View view) {
            switch (view.getId()) {
                case R.id.relHome:
                    viewPager.setCurrentItem(0);
                    relHome.setSelected(true);
                    relMycenter.setSelected(false);
                    break;
                case R.id.relMycenter:
                    if (!UserInfo.isLogin()) {
                        ARouter.getInstance().build(RouterMap.LOGIN_METNOD_PAGE).navigation();
                        return;
                    }
                    viewPager.setCurrentItem(1);
                    relMycenter.setSelected(true);
                    relHome.setSelected(false);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected int getContentResId() {
        return R.layout.activity_main;
    }

    @Override
    protected int getResId() {
        return 0;
    }

    @Override
    public String getPageTitle() {
        return "";
    }

    @Override
    protected CommonPresenter getPresenter() {
        return new CommonPresenter();
    }

    @Override
    protected MainModule getModule() {
        return new MainModule();
    }

    //请求成功，内容为空。不弹窗
    public boolean hasData(BaseResponse<UpdateData> updateResponse) {
        return updateResponse != null
                && !StringUtils.isEmpty(updateResponse.getData().getUrl())
                && !StringUtils.isEmpty(updateResponse.getData().getAppVersion())
                && !StringUtils.isEmpty(updateResponse.getData().getDesc())
                && !StringUtils.isEmpty(updateResponse.getData().getMD5());
    }

    @Override
    public void showResponse(int apiType, String listType, Object o) {
        if (apiType == HttpConstant.GOOGLE_PLAY_UPDATE_INFO) {
            final BaseResponse<UpdateData> updateResponse = (BaseResponse<UpdateData>) o;
            if (hasData(updateResponse)) {
                if (updateVersionDialog == null) {
                    updateVersionDialog = new UpdateVersionDialog(this, R.style.normal_dialog);
                }
                updateVersionDialog.setContent(getStringResource(R.string.new_version_code) +
                        updateResponse.getData().getAppVersion() + "\n" + updateResponse.getData
                        ().getDesc());
                updateVersionDialog.setTitle(getStringResource(R.string.checkout_new_version));
                if (updateResponse.getData().isUpdate()) {
                    updateVersionDialog.setCancelable(false);
                } else {
                    updateVersionDialog.setCancelable(true);
                }

                updateVersionDialog.setNormalClickListener(new UpdateVersionDialog
                        .NormalClickListener() {
                    @SuppressLint("CheckResult")
                    @Override
                    public void onConfirmClick() {

                        if (!updateResponse.getData().isUpdate()) {
                            DialogManager.getManager().dismissDialog(updateVersionDialog);
                        }
                        ApkUtils.launchAppDetail(MainActivity.this, updateResponse.getData()
                                .getpName());
                    }
                });
                DialogManager.getManager().showDialogStack(updateVersionDialog);
            }
        }
    }

    @Override
    public void showError(Throwable e) {
        ToastUtils.showShort(MainActivity.this, R.string.network_error);
        dismissLoadingView();
    }
}
